﻿namespace _4_NovaAdmin.Web.Core.Idempotency;

public class DatabaseIdempotencyStore : IIdempotencyStore, IScopedDependency
{
    private readonly AppDbContext _context;
    private readonly TimeSpan _expiration;

    public DatabaseIdempotencyStore(AppDbContext context, IOptions<IdempotencyOptions> options)
    {
        _context = context;
        _expiration = TimeSpan.FromHours(options.Value.ExpirationHours);
    }

    public async Task<bool> TryCreateRecordAsync(string key, string response)
    {
        try
        {
            _context.IdempotencyRecord.Add(new IdempotencyRecord
            {
                Key = key,
                Response = response,
                ExpireAt = DateTime.UtcNow.Add(_expiration)
            });
            await _context.SaveChangesAsync();
            return true;
        }
        catch (DbUpdateException ex)
        {
            return false;
        }
    }

    public async Task<string?> GetResponseAsync(string key)
        => (await _context.IdempotencyRecord
            .AsNoTracking()
            .FirstOrDefaultAsync(r => r.Key == key && r.ExpireAt > DateTime.UtcNow))?.Response;
}
